{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Contributed by Faisal Alkheraiji\n",
    "\n",
    "LinkedIn: https://www.linkedin.com/in/faisalalkheraiji/\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The first big project - Professionally You!\n",
    "\n",
    "### And, Tool use.\n",
    "\n",
    "### But first: introducing Telegram\n",
    "\n",
    "We need to do the following to get out Telegram chatbot working:\n",
    "\n",
    "1. Create new telegram bot using @BotFather.\n",
    "2. Get our bot token.\n",
    "3. Get your chat ID.\n",
    "\n",
    "For easy and quick tutorial, follow this great tutorial from our friend:\n",
    "\n",
    "https://chatgpt.com/share/686eccf4-34b0-8000-8f34-a3d9269e0578\n",
    "\n",
    "Then add 2 lines to your `.env` file:\n",
    "\n",
    "TELEGRAM*BOT_TOKEN=\\_your bot token*\n",
    "\n",
    "TELEGRAM*CHAT_ID=\\_your chat ID*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# imports\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "import json\n",
    "import os\n",
    "import requests\n",
    "from pypdf import PdfReader\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The usual start\n",
    "\n",
    "load_dotenv(override=True)\n",
    "openai = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Getting the Telegram bot token and chat ID from environment variables\n",
    "# You can also replace these with your actual values directly\n",
    "\n",
    "TELEGRAM_BOT_TOKEN = os.getenv(\"TELEGRAM_BOT_TOKEN\", \"your_bot_token_here\")\n",
    "TELEGRAM_CHAT_ID = os.getenv(\"TELEGRAM_CHAT_ID\", \"your_chat_id_here\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def send_telegram_message(text):\n",
    "    url = f\"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage\"\n",
    "    payload = {\"chat_id\": TELEGRAM_CHAT_ID, \"text\": text}\n",
    "\n",
    "    response = requests.post(url, data=payload)\n",
    "\n",
    "    if response.status_code == 200:\n",
    "        # print(\"Message sent successfully!\")\n",
    "        return {\"status\": \"success\", \"message\": text}\n",
    "    else:\n",
    "        # print(f\"Failed to send message. Status code: {response.status_code}\")\n",
    "        # print(response.text)\n",
    "        return {\"status\": \"error\", \"message\": response.text}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example usage\n",
    "send_telegram_message(\"Hello from python notebook !!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_user_details(email, name=\"Name not provided\", notes=\"not provided\"):\n",
    "    send_telegram_message(\n",
    "        f\"Recording interest from {name} with email {email} and notes {notes}\"\n",
    "    )\n",
    "    return {\"recorded\": \"ok\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_unknown_question(question):\n",
    "    send_telegram_message(f\"Recording {question} asked that I couldn't answer\")\n",
    "    return {\"recorded\": \"ok\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "record_user_details_json = {\n",
    "    \"name\": \"record_user_details\",\n",
    "    \"description\": \"Use this tool to record that a user is interested in being in touch and provided an email address\",\n",
    "    \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"email\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The email address of this user\",\n",
    "            },\n",
    "            \"name\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The user's name, if they provided it\",\n",
    "            },\n",
    "            \"notes\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"Any additional information about the conversation that's worth recording to give context\",\n",
    "            },\n",
    "        },\n",
    "        \"required\": [\"email\"],\n",
    "        \"additionalProperties\": False,\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "record_unknown_question_json = {\n",
    "    \"name\": \"record_unknown_question\",\n",
    "    \"description\": \"Always use this tool to record any question that couldn't be answered as you didn't know the answer\",\n",
    "    \"parameters\": {\n",
    "        \"type\": \"object\",\n",
    "        \"properties\": {\n",
    "            \"question\": {\n",
    "                \"type\": \"string\",\n",
    "                \"description\": \"The question that couldn't be answered\",\n",
    "            },\n",
    "        },\n",
    "        \"required\": [\"question\"],\n",
    "        \"additionalProperties\": False,\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [\n",
    "    {\"type\": \"function\", \"function\": record_user_details_json},\n",
    "    {\"type\": \"function\", \"function\": record_unknown_question_json},\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This function can take a list of tool calls, and run them. This is the IF statement!!\n",
    "\n",
    "\n",
    "def handle_tool_calls(tool_calls):\n",
    "    results = []\n",
    "    for tool_call in tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        print(f\"Tool called: {tool_name}\", flush=True)\n",
    "\n",
    "        # THE BIG IF STATEMENT!!!\n",
    "\n",
    "        if tool_name == \"record_user_details\":\n",
    "            result = record_user_details(**arguments)\n",
    "        elif tool_name == \"record_unknown_question\":\n",
    "            result = record_unknown_question(**arguments)\n",
    "\n",
    "        results.append(\n",
    "            {\n",
    "                \"role\": \"tool\",\n",
    "                \"content\": json.dumps(result),\n",
    "                \"tool_call_id\": tool_call.id,\n",
    "            }\n",
    "        )\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "globals()[\"record_unknown_question\"](\"this is a really hard question\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is a more elegant way that avoids the IF statement.\n",
    "\n",
    "\n",
    "def handle_tool_calls(tool_calls):\n",
    "    results = []\n",
    "    for tool_call in tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        arguments = json.loads(tool_call.function.arguments)\n",
    "        print(f\"Tool called: {tool_name}\", flush=True)\n",
    "        tool = globals().get(tool_name)\n",
    "        result = tool(**arguments) if tool else {}\n",
    "        results.append(\n",
    "            {\n",
    "                \"role\": \"tool\",\n",
    "                \"content\": json.dumps(result),\n",
    "                \"tool_call_id\": tool_call.id,\n",
    "            }\n",
    "        )\n",
    "    return results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "reader = PdfReader(\"../me/linkedin.pdf\")\n",
    "linkedin = \"\"\n",
    "for page in reader.pages:\n",
    "    text = page.extract_text()\n",
    "    if text:\n",
    "        linkedin += text\n",
    "\n",
    "with open(\"../me/summary.txt\", \"r\", encoding=\"utf-8\") as f:\n",
    "    summary = f.read()\n",
    "\n",
    "name = \"Ed Donner\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "system_prompt = f\"You are acting as {name}. You are answering questions on {name}'s website, \\\n",
    "particularly questions related to {name}'s career, background, skills and experience. \\\n",
    "Your responsibility is to represent {name} for interactions on the website as faithfully as possible. \\\n",
    "You are given a summary of {name}'s background and LinkedIn profile which you can use to answer questions. \\\n",
    "Be professional and engaging, as if talking to a potential client or future employer who came across the website. \\\n",
    "If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \\\n",
    "If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. \"\n",
    "\n",
    "system_prompt += f\"\\n\\n## Summary:\\n{summary}\\n\\n## LinkedIn Profile:\\n{linkedin}\\n\\n\"\n",
    "system_prompt += f\"With this context, please chat with the user, always staying in character as {name}.\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def chat(message, history):\n",
    "    messages = (\n",
    "        [{\"role\": \"system\", \"content\": system_prompt}]\n",
    "        + history\n",
    "        + [{\"role\": \"user\", \"content\": message}]\n",
    "    )\n",
    "    done = False\n",
    "    while not done:\n",
    "        # This is the call to the LLM - see that we pass in the tools json\n",
    "\n",
    "        response = openai.chat.completions.create(\n",
    "            model=\"gpt-4o-mini\", messages=messages, tools=tools\n",
    "        )\n",
    "\n",
    "        finish_reason = response.choices[0].finish_reason\n",
    "\n",
    "        # If the LLM wants to call a tool, we do that!\n",
    "\n",
    "        if finish_reason == \"tool_calls\":\n",
    "            message = response.choices[0].message\n",
    "            tool_calls = message.tool_calls\n",
    "            results = handle_tool_calls(tool_calls)\n",
    "            messages.append(message)\n",
    "            messages.extend(results)\n",
    "        else:\n",
    "            done = True\n",
    "    return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gr.ChatInterface(chat, type=\"messages\").launch(inbrowser=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#ff7800;\">Exercise</h2>\n",
    "            <span style=\"color:#ff7800;\">• First and foremost, deploy this for yourself! It's a real, valuable tool - the future resume..<br/>\n",
    "            • Next, improve the resources - add better context about yourself. If you know RAG, then add a knowledge base about you.<br/>\n",
    "            • Add in more tools! You could have a SQL database with common Q&A that the LLM could read and write from?<br/>\n",
    "            • Bring in the Evaluator from the last lab, and add other Agentic patterns.\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../../assets/business.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#00bfff;\">Commercial implications</h2>\n",
    "            <span style=\"color:#00bfff;\">Aside from the obvious (your career alter-ego) this has business applications in any situation where you need an AI assistant with domain expertise and an ability to interact with the real world.\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
